<template>
	<view>
		<view v-if="(!weightList || weightList.length <= 0) && noDataFlag" class="no_data">暂无数据，请先在首页添加体重数据。</view>

		<view class="type_out">
			<view class="type_item" :class="typeIndex == index ? 'select': ''" v-for="(item, index) in typeList"
				:key="index" @click="selectType(index)">{{item.name}}</view>
		</view>


		<!-- 从页面整洁度及代码可阅读性上来看，不再推荐使用原生canvas写法来调用uCharts -->
		<canvas :style="{height : ((maxHeight - navigationHeight - 100) > 100 ? maxHeight - navigationHeight - 100 : 800) + 'rpx', width: 750 + 'rpx'}" canvasId="canvasLine" id="canvasLine" class="charts"
			@tap="tap($event,'canvasLine')" />


		<!--  底部组件  -->
		<bottom-navigation :navigationIndex="1"></bottom-navigation>
	</view>
</template>

<script>
	import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/u-charts.js';

	var uChartsInstance = {};


	import {
		findWeightListApi
	} from '@/api/weightApi.js'
	import storageUtil from '@/utils/storageUtil.js'
	import {
		getDate,
		getYear,
		getMonth,
		getDay,
		getHour,
		getMinute,
		getSecond,
		compareDate,
		addDate,
		compareYearMonth,
		formatTime
	} from '@/utils/dateUtil.js'
	import {
		formatTimeByMothAndDay,
		formatTimeByYearAndMoth
	} from '@/utils/formatUtil.js'
	import toastUtil from '@/utils/toastUtil.js'
	import configUtil from '../../utils/config/configUtil.js'

	const app = getApp()


	export default {
		name: 'foldLine',
		data() {
			return {
				// 系统平台
				system: app.globalData.system,
				// 导航栏高度
				navigationHeight: app.globalData.navigationHeight,
				// 统一背景颜色
				unifyBgColor: app.globalData.unifyBgColor,
				// 顶部导航栏高度
				topNavigationHeight: app.globalData.topNavigationHeight,
				// 主色调
				mainColor: app.globalData.mainColor,
				// 最大的高度
				maxHeight: app.globalData.maxHeight,
				// ec 用于折线展示的数据
				ec: {},
				// 体重集合
				weightList: [],
				config: {},
				// 统计类型集合
				typeList: [{
					name: "近一月",
					value: "last_one_mouth",
				}, {
					name: "近三月",
					value: "last_three_mouth",
				}, {
					name: "近一年",
					value: "last_one_year",
				}, {
					name: "近五年",
					value: "last_five_year",
				}],
				// 类型下标
				typeIndex: 0,
				// 没有数据标志
				noDataFlag: false,
				// 这里初始化一个null，待会儿用来充当echarts实例
				myChart: null,
				opts: {
					// 不显示数据点
					dataLabel: false,
					series: {
						pointShape: "none",
						style: "curve",
						pointShape: "circle"
					},

					xAxis: {
						labelCount: 4,
						disableGrid: true
					},
					yAxis: {
						data:[{tofix:2}],
						format: function() {
							return ''
						}
						// data: [{
						// 	min: 0
						// }]
					},
					// extra: {
					// 	column: {
					// 		type: "group"
					// 	}
					// }
					extra: {
					    line: {
					        type: "curve",
					        width: 2,
					        activeType: "hollow"
					    },
						markLine: {
							dashLength: 4
						}
					}
				},
				chartData: {},
				cWidth: 350,
				cHeight: 300,
				pixelRatio: 1,
			}
		},

		onLoad(options) {

			setTimeout(() => {
				this.noDataFlag = true
			}, 1000)
			
			// //#ifdef MP-ALIPAY || MP-WEIXIN
			// this.pixelRatio = uni.getSystemInfoSync().pixelRatio;
			// //#endif
			this.cWidth = uni.upx2px(750);
			this.cHeight = uni.upx2px((this.maxHeight - this.navigationHeight - 100 - 120) > 100 ? this.maxHeight - this.navigationHeight - 100 - 120 : 800);
			console.log('this.cWidth : ', this.cWidth)
			console.log('this.cHeight : ', this.cHeight)
			
			// 查询目标体重
			this.getConfig();// 内部会查询全部体重，并渲染
		},
		onReady() {
			// this.findAllWeight()
		},
		methods: {
			
			/**
			 * 查询配置
			 */
			getConfig() {
				console.log("foldLine getConfig")
				toastUtil.showLoading()
				configUtil.getConfig().then((res) => {
					console.log('getConfig : ', res)
					// 查询成功
					let data = res
					// 查完了
					if (!data) {
						return
					}
					this.config = data
					console.log("config : ", this.config)
				}, (data) => {
					console.log('reject data : ', data)
					toastUtil.showToast(res.errMsg)
				}).finally(() => {
					toastUtil.hideLoading()
					// 查询全部体重，内部会渲染
					this.findAllWeight();
				})
			},

			drawCharts(id, data, minMaxArr) {
				let goalWeight = this.config.goalWeight
				console.log("drawCharts : ", goalWeight)
				const ctx = uni.createCanvasContext(id);
				uChartsInstance[id] = new uCharts({
			  //$this:this, //v2.0版本不需要再传canvasId和$this了，v1.0因为传$this会导致实例混乱
					//canvasId: canvasId, //v2.0版本不需要再传canvasId和$this了，v1.0因为传$this会导致实例混乱
					type: 'line',
					context: ctx, //v2.0版本必须要传context
					fontSize: 11,
					padding: [15, 15, 0, 15],
					categories: data.categories,
					series: data.series,
					animation: true,
					width: this.cWidth,
					height: this.cHeight,
					// 不显示数据点
					dataLabel: false,
					
					xAxis: {
						labelCount: 4,
						disableGrid: true
					},
					yAxis: {
						data:[{
							tofix:2,
							min: minMaxArr[0],
							max: minMaxArr[1]
						}],
						format: function() {
							return ''
						},
						// data: [{
						// 	min: 0
						// }]
					},
					extra: {
						line: {
							type: 'curve',
							width: 2
						},
						markLine: {
							dashLength: 4,
							type: "solid",
							data: [{
								value: goalWeight,
								labelFontSize: 10,
								labelOffsetX: -40,
								labelOffsetY: 8,
								labelBgOpacity: 0.5,
								labelPadding: 1,
								labelText: "目标体重",
								showLabel: goalWeight ? true : false,
								labelAlign: "bottom",
								lineColor: goalWeight ? "#DE4A42" : "#FFFFFF"
							}]
						}
					}
				});
			},
			
			tap(e, id) {
				uChartsInstance[id].showToolTip(e)
			},




			// 查找全部体重数据
			findAllWeight() {
				let form = {}
				// 根据何值分组
				let typeIndex = this.typeIndex
				if (typeIndex == 0) {
					form.groupField = "date"
					form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30)
				} else if (typeIndex == 1) {
					form.groupField = "date"
					form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3)
				} else if (typeIndex == 2) {
					form.groupField = "yearMonth"
					form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 12 * 1)
				} else {
					form.groupField = "yearMonth"
					form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 12 * 5)
				}
				form.openid = storageUtil.getOpenId()
				console.log("form : ", form)
				form.skip = 0
				form.pageSize = 100
				findWeightListApi(form).then((res) => {
					console.log('查询体重数据成功呢...... : ', res)
					console.log('全部体重数据 : ', res)
					this.weightList = res.data
					// 设置初始化函数
					this.resetOption()
					
				}, (res) => {
					console.log("调用查询体重异常 : ", res)
				}).finally((res) => {
					console.log("调用查询体重完成 : ", res)
				}).catch((res) => {
					console.log('异常 res : ', res)
				})
			},

			// 设置折线数据
			resetOption() {
				console.log('resetOption..........')
				let typeIndex = this.typeIndex
				let xList = []
				let valueList = []
				console.log('typeIndex : ', typeIndex)
				if (typeIndex == 0 || typeIndex == 1) {
					xList = this.getDateXList()
					valueList = this.getDateValueList(xList.length)
				} else {
					xList = this.getMonthXList()
					valueList = this.getMonthValueList(xList.length)
				}
				// 获取y的最大最小值
				console.log("xList : " + xList)
				console.log("valueList : " + valueList)
				console.log("getMinMaxArr   before ..........")
				var minMaxArr = this.getMinMaxArr();

				let options = {
					categories: xList,
					series: [{
						name: "体重",
						data: valueList,
						pointShape: 'none'
					}]
				};
				console.log('options : ', options)
				
				// 需要自行拼接chartsData
				let chartsData = {
					categories: xList,
					series: [{
						name: "体重",
						data: valueList,
						pointShape: xList.length < 10 ? "circle" : "none",
						style: "curve"
					}]
				}
				console.log('chartsData : ', chartsData)
				this.drawCharts("canvasLine", chartsData, minMaxArr);
			},

			// 获得x坐标集合
			getDateXList() {
				console.log('getDateXList.....')
				let weightList = this.weightList
				let xList = []
				// for (let i = 0; i < weightList.length; i++) {
				//   let item = weightList[i]
				//   //xList.push(item.dateTime)
				//   xList.push(item.dateTime)
				// }
				// 没有数据
				if (weightList.length == 0) {
					return xList
				}
				// 只有一个
				if (weightList.length == 1) {
					xList.push(formatTimeByMothAndDay(new Date(weightList[0].dateTime)))
					return xList
				}
				let startTime = new Date(weightList[0].dateTime)
				let startTimeStamp = startTime.getTime()
				let lastTime = new Date(weightList[weightList.length - 1].dateTime)
				lastTime.setHours(23, 59, 59, 999)
				let lastTimeStamp = lastTime.getTime()
				let typeIndex = this.typeIndex
				for (; startTimeStamp < lastTimeStamp; startTimeStamp = startTimeStamp + 60 * 60 * 24 * 1000) {
					xList.push(formatTimeByMothAndDay(new Date(startTimeStamp)))
				}
				console.log("xList : ", xList)
				return xList
			},

			// 获得x坐标集合
			getMonthXList() {
				console.log("getMonthXList.......")
				let weightList = this.weightList
				let xList = []

				// 没有数据
				if (weightList.length == 0) {
					return xList
				}
				// 只有一个
				if (weightList.length == 1) {
					xList.push(formatTimeByMothAndDay(new Date(weightList[0].dateTime)))
					return xList
				}
				let startTime = new Date(weightList[0].date)
				let lastTime = new Date(weightList[weightList.length - 1].date)
				// 设置为下个月的第一天第0秒
				// 增加一个月
				lastTime = addDate(lastTime, 0, 1)
				// 设置为第一天
				lastTime.setDate(1)
				// 设置为第0秒
				lastTime.setHours(0, 0, 0, 0)
				while(compareDate(startTime, lastTime) < 0){
					console.log("startTime : ", formatTimeByYearAndMoth(startTime))
					console.log("lastTime : ", formatTimeByYearAndMoth(lastTime))
					xList.push(formatTimeByYearAndMoth(new Date(startTime)))
					startTime = this.getNextMonth(startTime)
					console.log("startTime-add : ", formatTimeByYearAndMoth(startTime))
				}
				// for (; compareDate(startTime, lastTime) < 0; startTime = this.getNextMonth(startTime)) {
				// 	xList.push(formatTimeByYearAndMoth(new Date(startTime)))
				// }
				console.log("结果 ： xList : ", xList)
				return xList
			},

			// 获得下一个月的时间
			getNextMonth(date) {
				// 增加一个月时间
				date = addDate(date, 0, 1)
				console.log('next month : ', formatTimeByYearAndMoth(date))
				return date
			},

			// 获得x坐标的值集合
			getMonthValueList(maxLength) {
				console.log('getMonthValueList.........')
				let weightList = this.weightList
				let valueList = []
				// for (let i = 0; i < weightList.length; i++) {
				//   let item = weightList[i]
				//   //xList.push(item.dateTime)
				//   xList.push(item.dateTime)
				// }
				// 没有数据
				if (weightList.length == 0) {
					return valueList
				}
				// 只有一个
				if (weightList.length == 1) {
					valueList.push(weightList[0].weight)
					return valueList
				}
				let startTime = new Date(weightList[0].date)
				let startTimeStamp = startTime.getTime()
				let lastTime = new Date(weightList[weightList.length - 1].dateTime)
				// 设置为下个月的第一天第0秒
				// 增加一个月
				lastTime = addDate(lastTime, 0, 1)
				// 设置为第一天
				lastTime.setDate(1)
				// 设置为第0秒
				lastTime.setHours(0, 0, 0, 0)
				// 体重数据下标
				let weightIndex = 0
				for (; compareYearMonth(startTime, lastTime) <= 0 && valueList.length < maxLength; startTime = this
					.getNextMonth(startTime)) {
					console.log('weightIndex : ', weightIndex)
					console.log('startTime : ', formatTimeByYearAndMoth(startTime))
					console.log('lastTime : ', formatTimeByYearAndMoth(lastTime))
					// 体重item
					let itemWeight = weightList[weightIndex]
					let weightDate = new Date(itemWeight.date)
					let topWeight = itemWeight.weight
					// 当前item的时间
					let compareValue = compareYearMonth(startTime, weightDate)
					if (compareValue == -1) {
						valueList.push(topWeight)
					} else if (compareValue == 0) {
						valueList.push(topWeight)
					} else {
						weightIndex++
						topWeight = weightList[weightIndex].weight
						startTime = addDate(startTime, 0, -1)
					}
				}
				console.log("valueList : ", valueList)
				return valueList
			},

			// 获得x坐标的值集合
			getDateValueList(maxLength) {
				let weightList = this.weightList
				let valueList = []
				// for (let i = 0; i < weightList.length; i++) {
				//   let item = weightList[i]
				//   //xList.push(item.dateTime)
				//   xList.push(item.dateTime)
				// }
				// 没有数据
				if (weightList.length == 0) {
					return valueList
				}
				// 只有一个
				if (weightList.length == 1) {
					valueList.push(weightList[0].weight)
					return valueList
				}
				let startTime = new Date(weightList[0].dateTime)
				let startTimeStamp = startTime.getTime()
				let lastTime = new Date(weightList[weightList.length - 1].dateTime)
				lastTime.setHours(23, 59, 59, 999)
				let lastTimeStamp = lastTime.getTime()
				let topWeight = weightList[0].weight
				let weightIndex = 0
				for (; startTimeStamp <= lastTimeStamp && valueList.length < maxLength; startTimeStamp = startTimeStamp +
					60 * 60 * 24 * 1000) {
					let itemWeight = weightList[weightIndex]
					let weightDate = new Date(itemWeight.dateTime)
					let itemDate = new Date(startTimeStamp)
					let compareValue = compareDate(itemDate, weightDate)
					if (compareValue == -1) {
						valueList.push(topWeight)
					} else if (compareValue == 0) {
						valueList.push(topWeight)
					} else {
						weightIndex++
						topWeight = weightList[weightIndex].weight
						startTimeStamp = startTimeStamp - 60 * 60 * 24 * 1000
					}
				}
				console.log("valueList : ", valueList)
				return valueList
			},

			// 选择分类下标
			selectType(index) {
				if (index == this.typeIndex) {
					return
				}
				this.typeIndex = index
				// 刷新折线图
				this.findAllWeight()
			},
			
			/**
			 * 获取最大最小值下标
			 */
			getMinMaxArr(){
				console.log("getMinMaxArr   start ..........")
				let weightList = this.weightList
				// 没有体重数据，y为0-80
				if(!weightList){
					return [0, 80]
				}
				// 循环找出最大最小
				let max = 0;
				let min = 10000
				for(let i = 0 ; i < weightList.length ; i ++){
					let item = weightList[i]
					if(item.weight > max){
						max = item.weight
					}
					if(item.weight < min){
						min = item.weight
					}
				}
				// 判断目标体重线
				let goalWeight = this.config.goalWeight
				if(goalWeight < min){
					min = goalWeight
				}
				if(goalWeight > max){
					max = goalWeight
				}
				
				// 只有一个数字的话，+-2
				min = parseInt(min - 1)
				max = parseInt(max + 1)
				console.log("weightList : ", weightList)
				console.log(weightList)
				return [min, max]
			}
		}
	}
</script>

<style>
	/*  类型外部  */
	.type_out {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100rpx;
		width: 100%;
	}

	/*  类型项  */
	.type_item {
		width: 150rpx;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 25rpx;
		text-align: center;
		color: white;
		border: solid 1rpx white;
		border-radius: 10rpx;
		background-color: rgb(18, 150, 219);
	}

	.type_item.select {
		width: 150rpx;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 25rpx;
		text-align: center;
		color: rgb(18, 150, 219);
		border: solid 1rpx rgb(18, 150, 219);
		border-radius: 10rpx;
		background-color: white;

	}

	/*暂无数据*/
	.no_data {
		position: fixed;
		left: 0;
		top: 300rpx;
		width: 100%;
		text-align: center;
		height: 100rpx;
	}

	/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
	.charts-box {
		width: 100%;
		/* 		height: 300px; */
	}
</style>
